import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.api = api
}

//渲染进程触发自定义的事件，主进程接收到该事件，实现渲染进程到主进程的通信
const calljson = async (funcname, json) => {
  const resData = await ipcRenderer.invoke(funcname, json)
  return resData
}

//api.calljson = calljson
//将使用node模块的接口暴露给渲染进程使用
contextBridge.exposeInMainWorld('externalapi', {
  calljson
})
